import { Component, OnInit, ComponentFactoryResolver, ViewChild, OnDestroy } from '@angular/core';
import { DynamicHostDirective } from '../dynamic-host.directive';
import { DynamicChildComponentInterface, ComponentDefinition } from './dynamic-render-child-int';
import { DynamicChildAComponent } from './dynamic-render-childa.component';
import { DynamicChildBComponent } from './dynamic-render-childb.component';

@Component({
  selector: 'app-dynamic-render',
  templateUrl: './dynamic-render.component.html',
  styleUrls: ['./dynamic-render.component.css']
})
export class DynamicRenderComponent implements OnInit, OnDestroy {

  @ViewChild(DynamicHostDirective) dynamichhost: DynamicHostDirective;
  interval: any;
  currentIndex = -1;
  definitions: ComponentDefinition[];
  constructor(private componentFactoryResolver: ComponentFactoryResolver) { }

  ngOnInit() {
    this.definitions = [
      {type: DynamicChildAComponent, data: {name: 'Jim', id: 1}}
    , {type: DynamicChildBComponent, data: {name: 'Green', id: 2}}];
    this.loadComponent();
    this.activeInterval();
  }
  ngOnDestroy() {
    clearInterval(this.interval);
  }
  loadComponent() {
    if (this.currentIndex + 1 < this.definitions.length) {
      this.currentIndex++;
    } else {
      this.currentIndex = 0;
    }
    const definition = this.definitions[this.currentIndex];
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(definition.type);
    this.dynamichhost.viewContainerRef.clear();
    const componentRef = this.dynamichhost.viewContainerRef.createComponent(componentFactory);
    const component = <DynamicChildComponentInterface>componentRef.instance;
    component.data = definition.data;
  }
  activeInterval() {
    this.interval = setInterval(() => {
      this.loadComponent();
    }, 3000);
  }
}
